﻿using System;
using System.Collections.Generic;
using Gameplay.PVE.Utils;
using RootMotion.FinalIK;
using UnityEngine;
using UnityEngine.PlayerLoop;
using Yoozoo.Libs;

namespace Gameplay.PVE.Survivor
{
    /// <summary>
    /// 被击飞
    /// </summary>
    public class KnockFlyAction : ControlAction
    {
        private static float basicFlyTime = 1;
        private static float basicStandTime = 1.667f;
        private float flyTime = basicFlyTime;
        private float standTime = basicStandTime;

        private int state = 0;
        private float startTime;
        private float onGroundTime = 0;

        private Vector3 direction;
        private float distance;
        private float accelerate;
        private float speed;

        public override float GetDuration()
        {
            var duration = controlElement.config.duration;
            if (duration < basicStandTime + basicFlyTime)
            {
                duration = basicStandTime + basicFlyTime;
            }
            return duration;
        }

        public override void Start()
        {
            unit.SetBool("IsKnocking",true);
            unit.Play("KnockFlyStart",true);
            unit.SetSpeed(0);
            startTime = TimeManager.time;
            state = 0;
            direction = (unit.position - controlElement.sourcePosition);
            direction.y = 0;
            direction = direction.normalized;
            onGroundTime = GetDuration() - basicFlyTime - basicStandTime;
            var time = flyTime;
            distance = controlElement.config.value;
            accelerate = 2 * distance / time / time;
            speed = accelerate * time;
        }

        public override void Update()
        {
            if (state == 0)
            {
                if (TimeManager.time - startTime >= flyTime)
                {
                    state = 1;
                    //unit.Play("KnockFlyEnd",true);
                }
                speed -= accelerate * Time.deltaTime;
                unit.Position += direction * speed * Time.deltaTime;
            }
            if (state == 1)
            {
                if (TimeManager.time - startTime >= flyTime + onGroundTime)
                {
                    state = 2;
                    unit.Play("KnockFlyEnd",true);
                    unit.SetBool("IsKnocking",false);
                }
            }
            else if (state == 2)
            {
                
            }
        }

        public override void End()
        {
            if (unit.isDead)
            {
                return;
            }
            unit.SetBool("IsKnocking",false);
            unit.Play("Idle");
        }
    }
}
